package com.common.aop;

import com.common.controller.JsonResult;
import com.common.controller.ResultCode;
import com.common.exception.MyException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @classDescription:
 * @author:xiayingjie
 * @createTime:16/8/6
 */

@Component
@Aspect
public class ExceptionAOP {

    protected Gson gson = new GsonBuilder().create();

    @Pointcut(" execution(* com.*.controller.*..*(..))" )
    public void controller(){}

//    @Pointcut(" execution(* com.*.controller.*..*(..,Errors)) && args(..,errors)" )
//    public void validate(Errors errors){}



//    @AfterThrowing(throwing="ex",pointcut="controller()")
//    public void throwException(Throwable ex){
//        JsonResult js=(ex instanceof MyException)?new JsonResult( ((MyException) ex).getCode(),((MyException) ex).getMsg()):new JsonResult(ResultCode.EXCEPTION,ex.getMessage());
//
//        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
//
//        try {
//            PrintWriter out=response.getWriter();
//            response.setHeader("Content-Type", "application/json");
//            out.print(gson.toJson(js));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//    }

//    @Before("validate(errors)")
//    public void validateMethod(Errors errors){
//        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
//        if(errors.hasErrors()){
//            try {
//                JsonResult js=new JsonResult(ResultCode.PARAMS_ERROR,errors.getAllErrors().get(0).getDefaultMessage());
//                PrintWriter out=response.getWriter();
//                out.print(gson.toJson(js));
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//
//
//    }


}
